import { Component, OnInit, QueryList, ViewChildren,AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { DAGGraph, DAGTask, GitConfig } from '@api/git';
import { DDbodyComponent } from './ddbody/ddbody.component';
declare let jsPlumb: any;
declare let $      : any;
import {v4 as uuidv4}  from 'uuid';
import { GitManagerService } from '@common/services/git/gitmanager';



@Component({
  selector: 'kd-git-monitor',
  templateUrl: './git-monitor.component.html',
  styleUrls: ['./git-monitor.component.scss']
})
export class GitMonitorComponent implements OnInit ,AfterViewInit{
  dataSource: GitConfig[];
  selected:number;
  hello( ){
    console.log(this.selected  )
  }
  uploadDagTask( ){
    let gitmodel = this.dataSource[this.selected]
    let dagtask:DAGGraph={
      id:uuidv4(),
      Git_id:gitmodel.id,
      GitHash:"",
      Dir:gitmodel.path,
      tasks:this.tasklist,
    }
    this.git_.DagTaskCreate(dagtask).subscribe(
      data=> console.log(data+"\n.....save ok.....")
    )


  }
  @ViewChildren(DDbodyComponent) panes!: QueryList<DDbodyComponent>;
  constructor( 
    private readonly changeDetector: ChangeDetectorRef,
    private readonly git_: GitManagerService,
    ) { }
  heroes = [1,2,3]
  areaId = '#drop-bg'
  visoConfig = {
    // 基本连接线样式
    connectorPaintStyle: {
      lineWidth: 2,
      strokeStyle: '#61B7CF',
      joinstyle: 'round',
      fill: 'pink',
      outlineColor: '',
      outlineWidth: ''
    },// 鼠标悬浮在连接线上的样式
    connectorHoverStyle: {
      lineWidth: 2,
      strokeStyle: 'red',
      outlineWidth: 10,
      outlineColor: ''
    },
    baseStyle: {
      endpoint: ['Dot', {
        radius: 8,
        fill: 'pink'
      }], // 端点的形状
      connectorStyle: {
        lineWidth: 2,
        strokeStyle: '#61B7CF',
        joinstyle: 'round',
        fill: 'pink',
        outlineColor: '',
        outlineWidth: ''
      }, // 连接线的颜色，大小样式
      connectorHoverStyle: {
        lineWidth: 2,
        strokeStyle: 'red',
        outlineWidth: 10,
        outlineColor: ''
      },
      paintStyle: {
        strokeStyle: '#1e8151',
        stroke: '#7AB02C',
        fill: 'pink',
        fillStyle: '#1e8151',
        radius: 6,
        lineWidth: 2
      }, // 端点的颜色样式
      // hoverPaintStyle: {
      //   outlineStroke: 'pink'
      // },
      hoverPaintStyle: { stroke: 'blue' },
      isSource: true, // 是否可以拖动（作为连线起点）
      connector: ['Bezier', { gap: 10, cornerRadius: 5, alwaysRespectStubs: true }],  // 连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
      isTarget: true, // 是否可以放置（连线终点）
      maxConnections: -1, // 设置连接点最多可以连接几条线
      ConnectionsDetachable:false,
      connectorOverlays: [
        ['Arrow', {
          width: 10,
          length: 10,
          location: 1
        }],
        ['Arrow', {
          width: 10,
          length: 10,
          location: 0.2
        }],
        ['Arrow', {
          width: 10,
          length: 10,
          location: 0.7
        }],
        ['Label', {
          label: '',
          cssClass: '',
          labelStyle: {
            color: 'red'
          },
          events: {
          }
        }]
      ],
      baseArchors: ['RightMiddle', 'LeftMiddle']
    }
  }
  tasklist :DAGTask[] = [
    {
      id:uuidv4(),
      taskname:"task1",
      runprog:"" ,
      command:"", 
      depend:[],
    },

  ]

  dropNode(ui:any) {
    console.log(ui)
    var dag :DAGTask = {
      taskname: 'task',
      runprog: '',
      command: '',
      depend: [],
      id: uuidv4()
    }
    this.tasklist.push(dag)
    setTimeout(()=> {this.initJsPlumb(dag.id)} , 500)
    this.changeDetector.detectChanges();
  }
  ngOnInit(): void {
    this.git_.getGitConfig().subscribe(
      data => this.dataSource = data  
    )
  }
  
  ngAfterViewInit(){

    jsPlumb.setContainer('diagramContainer')
    $('.btn-controler').draggable({
      helper: 'clone',
      scope: 'ss'
    })
    //设定�??仍的区域
    $(this.areaId).droppable({
      scope: 'ss',
      drop: (event: any, ui: any) => {
        event;
        this.dropNode(ui)
      }
    })

    //ngAfterViewInit()
    jsPlumb.bind('dblclick', (conn: any, originalEvent: any) => {
      //this.deleteLine(conn);
      //originalEvent;
      console.log(conn)
      console.log(originalEvent)
    })

    // 当链接建
    jsPlumb.bind('beforeDrop', (info: any) => {
      //return this.connectionBeforeDropCheck(info)
      if(info.sourceId==info.targetId) return false
      for (let item of this.tasklist){
        if (item.id == info.targetId){
          item.depend.push(info.sourceId)
        }break;      
      }
      console.log(info)
      return true
    })

    jsPlumb.importDefaults({
      ConnectionsDetachable: true
    })

    for (let item of this.panes){
      this.initJsPlumb(item.id)
    }

  }
  initJsPlumb(id :string ){
    jsPlumb.draggable(id);
    this.setExitPoint(id, 'Bottom')
    this.setInPoint(id)
  }

  getBaseNodeConfig() {
    return Object.assign({}, this.visoConfig.baseStyle)
  }
  
  /**
   *  设置出口点
   * @param id 组件的id
   * @param position  出口点在那个位置 Bottom \Top \Left\Right
   */
  setExitPoint(id: any, position: any) {
    var config = this.getBaseNodeConfig()
    config.isTarget = false
    config.maxConnections = -1
    jsPlumb.addEndpoint(id,{
      anchors: position || 'Bottom',
      uuid: id + '-out'
    },config)
  }



  /**
   * 为当前组件设置入口点
   * @param uid 组件的id
   */
  setInPoint(id:any){    
    var config = this.getBaseNodeConfig()
    config.isSource = false
    config.maxConnections = -1
     jsPlumb.addEndpoint(id, {
      anchors: 'Top',
      uuid: id + '-in'
    },config)
  }


  Printdagtasks(){
    console.log(this.tasklist)
  }
}
